package cn.hucode.chapter2.util;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.DoubleRange;

/**
 * @author jiajian
 * @date 2016/12/4
 */
public final class CastUtil {
    public static String castString(Object object) {
        return CastUtil.castString(object, "");
    }

    private static String castString(Object object, String defaultValue) {
        return object != null ? String.valueOf(object) : defaultValue;
    }

    public static double castDouble(Object object) {
        return CastUtil.castDouble(object, 0);
    }

    private static double castDouble(Object object, double defaultValue) {
        double value = defaultValue;
        if (object != null) {
            String stringValue = castString(object);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    value = Double.parseDouble(stringValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }

    public static int castInt(Object object) {
        return CastUtil.castInt(object, 0);
    }

    private static int castInt(Object object, int defaultValue) {
        int value = defaultValue;
        if (object != null) {
            String stringValue = castString(object);
            if (StringUtils.isNotEmpty(stringValue)) {
                try {
                    value = Integer.parseInt(stringValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }
    public static boolean castBoolean(Object object) {
        return CastUtil.castBoolean(object, false);
    }

    private static boolean castBoolean(Object object, boolean defaultValue) {
        boolean value = defaultValue;
        if (object != null) {
            String stringValue = castString(object);
            value = Boolean.parseBoolean(stringValue);
        }
        return value;
    }


}
